<template>
  <view class="container">
    <!-- {{ xhrRespList }} -->
    <view
      class="px-40 py-30"
      style="background-color: rgba(255, 228, 181, 1)"
      v-if="routerDetail.advertisement"
    >
      <mp-html :content="routerDetail.advertisement" />
    </view>

    <view class="top-balance" v-if="0">
      <view class="balance">Balance: {{ coinNumber }} Piso</view>
      <view class="balance">
        Store Name : {{ package.store_name || "None" }}
      </view>
      <view class="balance">
        Package Expiry Time : {{ package.package_expiry_time || "Expired" }}
      </view>
      <view class="balance">
        Available Data : {{ package.available_data || "None" }}
      </view>
      <image
        src="../../static/coin.png"
        mode="aspectFit"
        style="
          width: 200rpx;
          height: 200rpx;
          position: absolute;
          right: 50rpx;
          top: 30rpx;
        "
      ></image>
    </view>
    <view class="infoBox">
      <!-- <view class="header"> The best connections wifi machine </view> -->
      <view class="mb-60">
        <view class="xinhao pt-40">
          <image
            src="../../static/xinhao1.png"
            mode="aspectFit"
            v-show="!is_online"
          ></image>
          <image
            src="../../static/xinhao2.png"
            mode="aspectFit"
            v-show="is_online"
          ></image>
          <text :style="is_online ? 'color:#21a049' : 'color:#d81e06'">{{
            is_online ? "Connected" : "Not Connected"
          }}</text>
        </view>

        <view class="flex justify-center mt-20" v-if="is_online">
          <az-count-down
            :seconds="timeSeconds"
            :minutes="timeMinutes"
            :hours="timeHours"
          />
        </view>

        <view class="info">
          Package Expiry Time : {{ package.package_expiry_time || "Expired" }}
        </view>
        <!--        <view class="info" v-if="infoMac"> Your ID: {{ infoMac }} </view>
        <view class="info"> Your Account: {{ account }} </view> -->
      </view>
      <view class="info">
        <!-- <view class=""> IP:{{ cip }} | MAC:{{ routerMac }} </view> -->
        <view class="flex-center mb-30">
          <view class="text-32 mr-20">Balance: </view>
          <view
            class="text-50 font-700"
            :style="{ color: coinNumber > 0 ? '#0082ff' : '#e90a0a' }"
          >
            {{ coinNumber }} Piso</view
          >
        </view>

        <view class="btns px-30">
          <view
            class="btn"
            style="background-color: #21a049; width: 350rpx"
            @click="insertCoin"
          >
            Insert Money
          </view>
        </view>

        <view class="btns px-30" v-if="routerDetail.enable_gcash == 1">
          <view
            class="btn"
            style="background-color: #0082ff; width: 350rpx"
            @click="openGCash = true"
          >
            G-Cash
          </view>
        </view>
      </view>
    </view>
    <view class="">
      <!-- <image src="../../static/coin.png" mode="aspectFit"
				style="width: 100rpx;height: 100rpx;margin: 60rpx auto 30rpx;display: block;"></image>
			<view class="" style="text-align: center; color: #ffd172;font-size: 35rpx;">
				PHP{{coinNumber}}
			</view> -->
      <!-- <view class="package-info" v-if="package!=[]">
				<view class="">
				</view>
				<view class="package-expiry-time">
				</view>
				<view class="package-expiry-time">
				</view>
				<view class="package-expiry-time">
				</view>
			</view> -->
    </view>
    <!-- <view class="machine-list" v-if="machines.length > 0">
      <text>{{ $t("Choose a nearby coin machine") }}:</text>
      <picker mode="selector" :range="machines" @change="onMachineChange" style="margin-top: 40rpx;">
				<view class="picker">{{ selectedMachine }}</view>
			</picker>
      <view class="card">
        <view
          class="item"
          :class="selectedMachineIndex == index ? 'active' : ''"
          v-for="(item, index) in machines"
          :key="index"
          @click="onMachineChange(index, item)"
        >
          {{ item.code }},{{ item.description }},{{
            item.status == 0 ? "Available" : "In use"
          }}
        </view>
        <view class="btn" @click="connectMachine">
          {{
            isConnectedCoin ? $t("Connected") + selectedMachine : $t("Connect")
          }}
        </view>
      </view>
    </view> -->
    <view
      class="cardShow"
      v-show="show"
      @click="show = false"
      @touchmove.stop.prevent="moveHandle"
    >
      <view class="box" @click.stop>
        <view class="title"> Choose a coin vendo </view>
        <scroll-view
          scroll-y="true"
          style="height: 560rpx"
          :show-scrollbar="true"
        >
          <view class="">
            <view
              class="item"
              :class="selectedMachineIndex == index ? 'active' : ''"
              v-for="(item, index) in machines"
              :key="index"
              @click="onMachineChange(index, item)"
            >
              <view class="" style="display: flex; align-items: end">
                <view
                  class=""
                  style="
                    font-size: 34rpx;
                    font-weight: 700;
                    margin-right: 10rpx;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    max-width: 45%;
                  "
                >
                  {{ item.code }}
                </view>
                <view
                  class=""
                  style="
                    font-size: 24rpx;
                    font-weight: 500;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    max-width: 45%;
                  "
                >
                  {{ item.description }}
                </view>
              </view>
              <view class="">
                status:
                <text
                  :style="
                    item.isAvailable == 1 ? 'color:#21a049' : 'color:#ec514f'
                  "
                >
                  {{ availableMap[item.isAvailable] }}</text
                >
              </view>
              <view
                class=""
                style="
                  position: absolute;
                  right: 30rpx;
                  top: 50%;
                  transform: translateY(-50%);
                "
                v-show="selectedMachineIndex == index"
              >
                <image
                  src="../../static/select.png"
                  mode="aspectFit"
                  style="width: 40rpx; height: 40rpx"
                ></image>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="btn" @click="connectMachine">
          {{
            isConnectedCoin
              ? $t("Connected") + selectedMachine
              : $t("Insert Coin")
          }}
        </view>
      </view>
    </view>
    <view class="px-40 pt-60" v-if="myGoodsList.length > 0">
      <az-card
        className="mb-30"
        :styleObj="{
          boxShadow: '0rpx 0rpx 24rpx 0rpx rgba(54, 101, 186, 0.2)',
        }"
      >
        <view class="px-30 pb-30 pt-20">
          <view
            v-for="(item, index) in myGoodsList"
            :key="index"
            class="flex items-center justify-between py-20"
            @click="onSelectGoods(item, index)"
          >
            <view class="flex items-center">
              <view class="font-700">
                <!-- <view class="mb-20">{{ item.title }}</view> -->
                <!--                <view
                  >Validity period: {{ formatTime(item.validity_period) }}H，{{
                    item.price
                  }}PHP，{{ item.internet_data }}G</view
                >
              </view> -->
                <view :style="{ color: item._disabled ? '#999' : '#000' }"
                  >{{ item.price }}Piso &nbsp&nbsp&nbsp{{ item.title }}</view
                >
              </view>
            </view>
            <view class="color-primary flex-shrink-0 ml-20">
              <az-icon
                v-show="!item._disabled && goodsIndex === index"
                :size="50"
                src="/static/radio-fill.png"
              />
              <az-icon
                v-show="!item._disabled && goodsIndex !== index"
                :size="50"
                src="/static/radio.png"
              />
              <az-icon
                v-show="item._disabled"
                :size="50"
                src="/static/radio-disabled.png"
              />
            </view>
          </view>
        </view>

        <view class="btns px-30">
          <!-- <view
            class="btn"
            style="background-color: #21a049"
            @click="insertCoin"
          >
            Insert Money
          </view> -->
          <!-- <view class="btn" style="background-color: #0082fc;" @click="coin" v-if="startInsert">
				Coining
			</view> -->
          <!-- <view
        class="btn"
        style="
          font-weight: 700;
          background-color: #ec514f;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        "
        @click="chooseMachine"
      >
        {{
          selectedMachine
            ? `Coin Machine: ${selectedMachine}`
            : "Choose a nearby coin machine"
        }}
      </view> -->
          <view
            class="btn flex items-center justify-center"
            style="font-weight: 700; background-color: #0082ff"
            v-if="coinNumber > 0 || getTime() || 1"
            @click="goOnlie"
          >
            <u-loading-icon
              v-if="goOnlineLoading"
              class="mr-20"
              color="#fff"
              size="18"
            ></u-loading-icon>
            <view>Go online immediately</view>
          </view>
        </view>
      </az-card>
    </view>

    <view
      v-else
      class="px-32 text-40 text-center"
      style="color: rgb(216, 30, 6)"
      >Please contact the merchant to activate package</view
    >

    <view class="info" v-if="infoMac"> Your ID: {{ infoMac }} </view>
    <view class="info pb-30"> Your Account: {{ account }} </view>
    <view>
      <!-- 遮罩层 -->
      <view class="overlay" v-if="startInsert"></view>
      <!-- 弹出层 -->
      <view class="popup" v-if="startInsert">
        <view class="popup-content">
          <!-- <view style="word-wrap: break-word">
            {{ topicList }}
          </view>
          <view style="word-wrap: break-word"> 价格：{{ price }} </view> -->

          <view
            class="popup-body"
            style="position: relative; text-align: center; font-size: 42rpx"
          >
            <u-icon
              name="close-circle"
              color="#999"
              size="28"
              style="position: absolute; top: 10rpx; right: 10rpx"
              @click="closePopup"
            ></u-icon>
            <view class="mt" style="color: #0082ff; font-weight: 700">
              Please Insert Money
            </view>
            <view class="" style="font-size: 34rpx">
              Waiting for {{ countdown }} seconds
            </view>
            <image
              src="../../static/pleaseCoining.png"
              mode="aspectFit"
              style="width: 80%; margin-top: 15rpx"
            ></image>
            <view class="mt">
              <text style="color: black; font-size: 30rpx"
                >Max Coin: {{ this.max_coin_num }}</text
              >
            </view>
            <view class="mt">
              Total Amount:
              <text style="color: red"> Piso {{ droppingCoinNumber }}</text>
            </view>

            <view class="mt">
              Total Credits:<text style="color: red">
                {{ coinTime || "0min" }}</text
              >
            </view>
            <view class="mt btnDone" @click="closePopup">
              I'm Done Paying
            </view>
            <view class="kaleidoscope"></view>
          </view>
          <view class="popup-footer">
            <!-- <u-button type="primary" :text="$t('确定')" @click="confirm" style="width: 30%;"></u-button> -->
            <!-- <u-button type="info" :text="$t('关闭')" @click="closePopup" style="width: 30%;"></u-button> -->
          </view>
        </view>
      </view>
    </view>

    <az-popup
      v-model="openGCash"
      :title="`G-Cash`"
      :zIndex="998"
      :overlayStyle="{ zIndex: 997 }"
      class="az_popup"
    >
      <view class="pb-30">
        <scroll-view scroll-y style="height: 100%">
          <div class="px-42">
            
                    <view class="px-30 pb-30 pt-20" style="display:flex; flex-direction: column; gap:30px;">
                         <div style="display:flex; justify-content: center; align-items: center; border:1px solid #8a8a8a; border-radius: 10px; padding-top:15px; padding-bottom: 10px;" @click="chooseAmount(100)">
							 <div><span style="font-weight: 700; font-size: 20px; padding-right: 5px;">100</span> php</div>
						 </div>
						 <div style="display:flex; justify-content: center; align-items: center; border:1px solid #8a8a8a; border-radius: 10px; padding-top:15px; padding-bottom: 10px;" @click="chooseAmount(500)">
						 	<div><span style="font-weight: 700; font-size: 20px; padding-right: 5px;">500</span> php</div>
						 </div>
						 <div style="display:flex; justify-content: center; align-items: center; border:1px solid #8a8a8a; border-radius: 10px; padding-top:15px; padding-bottom: 10px;" @click="chooseAmount(1000)">
						 	<div><span style="font-weight: 700; font-size: 20px; padding-right: 5px;">1000</span> php</div>
						 </div>
                    </view>
                
				           <div class="flex-center flex-col">
				              <div class="my-10">
								  <label>Please input the amount</label>
				              	  <input class="input" v-model="amount" :placeholder="$t(`amount`)" placeholder-style="color:#C38D5D" style="text-align: center; border-bottom: 1px solid #8a8a8a; margin-top: 10px; margin-bottom: 10px;" />
				              </div>
							  <u-button type="primary" :text="$t('Pay Now')" @click="goToPay" style="width: 30%; margin-top: 5px; margin-bottom: 5px;"></u-button>
				          </div>
              
            </div>
          </div>
        </scroll-view>
      </view>
    </az-popup>
  </view>
</template>

<script>
import TipUtils from "@/utils/tip.js";
import dayjs from "@/plugin/dayjs/dayjs.min.js";
import mqtt from "mqtt";
import {
  getUrlData,
  loginNew,
  machineListUser,
  machineListen,
  storeRouterProductList,
  startMachine,
  getRouter,
  sendMagToAllMachine,
} from "@/api/user";
export default {
  data() {
    return {
      goOnlineLoading: false,
      is_online: false,
      currentPage: "",
      openGCash: false,
      account: "",
      max_coin_num: "",
      infoMac: "",
      startInsert: false,
      coinNumber: 0,
      droppingCoinNumber: 0,
      coinTime: "",
      coinDevice: "",
      routerMac: "",
      mac: "",
      isConnected: false,
      messages: [],
      machines: [],
      selectedMachine: "",
      selectedMachineIndex: -1,
      isConnectedCoin: false,
      coinSubTopic: "",
      coinPubTopic: "",
      goodsList: [],
      goodsIndex: -1,
      countdown: 30,
      timer: null,
      price: 1,
      uid: "",
      package: {},
      isWifi: false,
      show: false,
      routerDetail: {
        advertisement: "",
      },
      xhrRespList: [],
      topicList: [],
      availableMap: {
        1: "Available",
        2: "In use",
        3: "Offline",
      },
      coinBgPlayerCtx: null,
      coinPlayerCtx: null,
      timeSeconds: 0,
      timeMinutes: 0,
      timeHours: 0,
      countDownIntervalId: null,
	  amount:0,
    };
  },
  created() {
    // this.getRouter();
    // 每隔 5 秒请求一次接口
    this.intervalId = setInterval(this.fetchData, 5000);
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.intervalId);
    this.stopCountDown();
  },
  computed: {
    myGoodsList() {
      return this.goodsList.map((goods) => ({
        ...goods,
        _disabled: goods.price > this.coinNumber,
      }));
    },
    crtSelectedMachine() {
      if (this.selectedMachineIndex === -1 || this.machines.length === 0)
        return;
      return this.machines[this.selectedMachineIndex];
    },
  },
  onLoad(e) {
    // this.sendRequest(function(error, response) {
    // 	if (error) {
    // 		alert(error);
    // 	} else {
    // 		alert(response);
    // 	}
    // });

    let curPage = getCurrentPages();
    this.currentPage = curPage[curPage.length - 1].route;
    this.routerMac = e.gw_mac || "00:11:22:33:44:55";
    this.mac = e.c_mac || "66:77:88:99:AA:BB";
    this.cip = e.c_ip;
    if (!uni.getStorageSync("GUID")) {
      this.account = "";
      //uni.setStorageSync("GUID", this.generateGUID());
    } else {
      this.account = uni.getStorageSync("GUID");
    }
    console.log(uni.getStorageSync("GUID"));
    this.login();
  },
  onShow() {
    this.startMachineInterval();
    this.createCoinBgPlayer();
    this.createCoinPlayer();
  },
  onHide() {
    this.stopMachineInterval();
  },
  methods: {
	  goToPay(){
		  
		  if(this.amount == 0){
		  	 alert("please put amount greater than 0"); 
		  	 return;
		  }
		  
		  let uid = this.uid;
		  let agent_id = this.routerDetail.uid
		  let mac = this.mac
		  location.href = 'https://pay.sharewifi.cc/cart/?quantity='+this.amount+'&uid='+this.uid+'&mac='+this.mac+'&agent_id='+this.agent_id  
	  },
	  chooseAmount(amount){
		  this.amount = amount
	  },
    startCountDown() {
      this.updateCountDown();
      this.countDownIntervalId = setInterval(() => {
        this.updateCountDown();
      }, 1000);
    },
    stopCountDown() {
      if (this.countDownIntervalId) clearInterval(this.countDownIntervalId);
    },
    updateCountDown() {
      const totalSeconds = this.getSecondsFromTimeNow();
      if (totalSeconds <= 0) {
        this.stopCountDown();
        return;
      }
      const { seconds, minutes, hours } =
        this.getFormattedTimeFromSeconds(totalSeconds);
      this.timeSeconds = seconds;
      this.timeMinutes = minutes;
      this.timeHours = hours;
    },
    getFormattedTimeFromSeconds(totalSeconds, format) {
      const {
        seconds: secondsValue,
        minutes,
        hours,
      } = this.getTimeFromSeconds(totalSeconds);
      const ampm = format === "12-hour" ? (hours >= 12 ? "pm" : "am") : "";
      const hoursValue = format === "12-hour" ? hours % 12 : hours;

      return {
        seconds: secondsValue,
        minutes,
        hours: hoursValue,
        ampm,
      };
    },
    getTimeFromSeconds(secs) {
      const totalSeconds = Math.ceil(secs);
      const days = Math.floor(totalSeconds / (60 * 60 * 24));
      const hours = Math.floor(totalSeconds / (60 * 60));
      const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
      const seconds = Math.floor(totalSeconds % 60);
      // console.log("seconds===>", seconds);

      return {
        seconds,
        minutes,
        hours,
        days,
      };
    },
    getSecondsFromTimeNow() {
      return dayjs(this.package.package_expiry_time).diff(dayjs(), "second");
    },
    createCoinBgPlayer() {
      this.coinBgPlayerCtx = uni.createInnerAudioContext();
      this.coinBgPlayerCtx.loop = true;
      this.coinBgPlayerCtx.src = "/static/audio/coin-bg.mp3";
      this.coinBgPlayerCtx.onPlay(() => {
        console.log("开始播放");
      });
      this.coinBgPlayerCtx.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
      });
    },
    onPlayCoinBgPlayer() {
      this.coinBgPlayerCtx.play();
    },
    onStopCoinBgPlayer() {
      this.coinBgPlayerCtx.stop();
    },
    createCoinPlayer() {
      this.coinPlayerCtx = uni.createInnerAudioContext();
      this.coinPlayerCtx.src = "/static/audio/coin.mp3";
      this.coinPlayerCtx.onPlay(() => {
        console.log("开始播放");
      });
      this.coinPlayerCtx.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
      });
    },
    onPlayCoinPlayer() {
      this.coinPlayerCtx.play();
    },
    // createCoinPlayer() {
    //   this.coinPlayerCtx = uni.createInnerAudioContext();
    //   this.coinPlayerCtx.src = "/static/audio/coin.mp3";
    //   this.coinPlayerCtx.onPlay(() => {
    //     console.log("开始播放");
    //   });
    //   this.coinPlayerCtx.play();
    // },

    checkRealInternetConnection() {
      var myHeaders = new Headers();
      myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
      myHeaders.append("Accept", "*/*");
      //myHeaders.append("Host", "api.ipify.org");
      //myHeaders.append("Host", "https://crmeb.sharewifi.cc/ipify-api/");
      //myHeaders.append('Cache-Control', 'no-store');
      //myHeaders.append('cache', 'no-store');
      myHeaders.append("Connection", "keep-alive");

      var requestOptions = {
        method: "GET",
        headers: myHeaders,
        redirect: "error",
      };

      fetch(
        `https://api.myip.la?timestamp=${new Date().getTime()}`,
        requestOptions
      )
        .then((response) => response.text())
        .then((result) => {
          this.is_online = true;
          //alert(result)
        })
        .catch((error) => {
          this.is_online = false;
          if (this.getTime()) {
            this.auth();
          }

          //alert('error', error)
        });
    },

    onCopy(val) {
      console.log("val===>", val);
      uni.setClipboardData({
        data: val,
        success() {
          uni.showToast({ title: "copy successful" });
        },
      });
    },
    moveHandle() {},
    startMachineInterval() {
      this.machineInterval = setInterval(() => {
        this.machineList();
      }, 3000);
    },
    stopMachineInterval() {
      if (this.machineInterval) {
        clearInterval(this.machineInterval);
      }
    },
    chooseMachine() {
      this.machineList();
      this.show = true;
      if (this.machines.length == 0) {
        TipUtils.showToast({
          title: "There are no coin acceptors available at this time.",
        });
      }
    },
    async getLocalIP() {
      return new Promise((resolve, reject) => {
        if (
          window.RTCPeerConnection ||
          window.webkitRTCPeerConnection ||
          window.mozRTCPeerConnection
        ) {
          console.log("RTCPeerConnection is supported");
          // return resolve();
        } else {
          console.log("RTCPeerConnection is not supported");
        }

        console.log("window.RTCPeerConnection===>", window.RTCPeerConnection);
        const peerConnection = new RTCPeerConnection({
          iceServers: [],
        });
        peerConnection.createDataChannel("");
        peerConnection
          .createOffer()
          .then((offer) => peerConnection.setLocalDescription(offer));

        peerConnection.onicecandidate = (event) => {
          if (!event || !event.candidate) {
            peerConnection.close();
            return;
          }

          const ipMatch = /([0-9]{1,3}(\.[0-9]{1,3}){3})/.exec(
            event.candidate.candidate
          );
          if (ipMatch) {
            resolve(ipMatch[1]);
          }
        };
      });
    },
    async auth() {
      // 获取路由器MAC、手机MAC、手机局域网IP和手机主机名（需要通过合适的API获取）
      const routerMac = this.routerMac;
      const phoneMac = this.mac;
      const lanIp = this.cip;
      const hostname = "myPhone";
      this.getLocalIP()
        .then((ip) => {
          console.log("Local IP: " + ip);
        })
        .catch(console.error);
      // 构建请求数据
      const requestData = `${uni.getStorageSync("GUID")} 88888888`;
      console.log(requestData);
      // return requestData
      // 创建TCP连接并发送数据

      // uni.request({
      // 	url: 'http://10.11.12.1:30098',
      // 	method: "POST",
      // 	data: requestData,
      // 	success(res) {
      // 		console.log(res);
      // 		if(res.data== 1){
      // 			this.isWifi = true
      // 		}
      // 	}
      // })
      // this.sendRequest(function(error, response) {
      // 	if (error) {
      // 		alert(error);
      // 	} else {
      // 		// alert(response);
      // 		let newStr =response.substring(1);
      // 		window.open(newStr,"_blank")
      // 	}
      // });
      var xmlhttp = new XMLHttpRequest();
      const that = this;
      xmlhttp.onreadystatechange = function () {
        console.log("xmlhttp.status===>", xmlhttp.status);
        console.log("xmlhttp.readyState===>", xmlhttp.readyState);
        that.xhrRespList.push({
          status: xmlhttp.status,
          readyState: xmlhttp.readyState,
          responseText: xmlhttp.responseText,
        });

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          const [status, msg] = xmlhttp.responseText.split(" ", 2);
          if (status == 1) {
            // window.location.href = `intent:${msg}#Intent;end`;
            const url = `${msg}?gw_mac=${that.routerMac}&c_mac=${that.mac}&c_ip=${that.cip}&gw_ip=10.11.12.1`;
            window.location.href = url;
          }
          if (status == 0) {
            TipUtils.showToast({ title: msg });
          }
        } else {
          if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
            alert("Network error!" + xmlhttp.readyState + "|" + xmlhttp.status);
            //alert("Network error!" + xmlhttp.responseText);
          }
        }
        that.goOnlineLoading = false;
      };
      xmlhttp.onerror = function () {
        that.goOnlineLoading = false;
      };
      //xmlhttp.open("POST", "http://10.11.12.1:30098", true);
      xmlhttp.open("POST", "https://localrouter.sharewifi.cc:30098", true);
      that.goOnlineLoading = true;
      xmlhttp.withCredentials = true;
      //xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
      xmlhttp.send(`${uni.getStorageSync("GUID")} 88888888`);

      return;
    },
    sendRequest(callback) {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
          if (xmlhttp.status == 200) {
            var response = xmlhttp.responseText.replace(/\s+/g, "");
            callback(null, response);
          } else {
            callback(`网络错误! ${xmlhttp.readyState} | ${xmlhttp.status}`);
          }
        }
      };
      xmlhttp.open("POST", "http://10.11.12.1:30098", true);
      xmlhttp.withCredentials = true;
      xmlhttp.setRequestHeader(
        "Content-Type",
        "application/x-www-form-urlencoded"
      );
      xmlhttp.send(`${uni.getStorageSync("GUID")} 88888888`);
    },
    getTime() {
      if (!this.package) return;
      // 获取当前时间戳，精确到毫秒
      const currentTimestamp = Date.now();

      // 将 package_expiry_time 转换为时间戳
      const packageExpiryTime = dayjs(
        this.package.package_expiry_time
      ).valueOf();
      // console.log("packageExpiryTime", packageExpiryTime);
      // console.log("currentTimestamp", currentTimestamp);
      // 判断 package_expiry_time 是否大于当前时间
      if (packageExpiryTime > currentTimestamp && !isNaN(packageExpiryTime)) {
        return true;
      } else {
        return false;
      }
    },
    loadProducts() {
      storeRouterProductList().then((res) => {
        if (res.data.data) {
          this.goodsList = res.data.data;
        }
      });
    },
    isAvailable(item) {
      if (!item.heartbeat_time) return 3;
      const currentTimestamp = Date.now();

      if (item.heartbeat_time) {
        const heartbeatTimestamp = dayjs(item.heartbeat_time).valueOf();
        const timeDifference = currentTimestamp - heartbeatTimestamp;
        const timeThreshold = 1000 * 60 * 2; // 30s
        if (!(timeDifference < timeThreshold)) return 3;
      }

      if (!item.last_use_time) return 2;
      if (item.last_use_time) {
        const heartbeatTimestamp = dayjs(item.last_use_time).valueOf();
        const timeDifference = currentTimestamp - heartbeatTimestamp;
        const timeThreshold = 1000 * 30; // 30s
        if (!(timeDifference > timeThreshold)) return 2;
      }
      return 1;
    },
    machineList() {
      machineListUser().then((res) => {
        // let firstIndex = -1;
        this.machines = res.data.data.map((item, index) => {
          const v = this.isAvailable(item);
          // if (firstIndex === -1 && v) firstIndex = index;
          return {
            ...item,
            isAvailable: v,
          };
        });

        // if (this.machines.length > 0 && firstIndex !== -1) {
        //   this.onMachineChange(firstIndex, this.machines[firstIndex]);
        // }
      });
    },
    onMachineChange(index, item) {
      if (item.isAvailable != 1) return;
      if (index != this.selectedMachineIndex) {
        this.isConnected = false;
      }
      console.log("onMachineChange topic===>", item.coin_sub_topic);
      console.log("item====>", item);

      this.coinSubTopic = item.coin_sub_topic;
      this.coinPubTopic = item.coin_pub_topic;
      this.beep_volume = item.beep_volume;
      this.max_coin_num = item.max_coin_num;
      this.coin_time = item.coin_time;
      this.price = Number(item.price);
      this.selectedMachine = this.machines[index].code;
      this.selectedMachineIndex = index;
    },
    connectMachine() {
      if (this.selectedMachineIndex === -1) {
        TipUtils.showToast({
          title: "There are no coin acceptors available at this time.",
        });
        return;
      }
      let data = {
        topic: this.coinSubTopic,
      };
      // this.insertCoin()
      // return
      console.log("onConnect coinSubTopic===>", this.coinSubTopic);

      machineListen(data)
        .then((res) => {
          console.log("res===>", res);
          if (res.status == 200) {
            // this.coinSubTopic = 'PISO_WIFI/Coin/Sub/CC:7B:5C:24:CF:94'
            // this.coinPubTopic = 'PISO_WIFI/Coin/Pub/CC:7B:5C:24:CF:94';
            this.insertCoin();
            sendMagToAllMachine();
          } else {
          }
        })
        .catch((e) => {
          uni.showToast({
            title: e,
            icon: "none",
          });
        });
    },
    async goOnlie() {
      if (this.goOnlineLoading) return;
      this.goOnlineLoading = true;
      if (this.routerDetail.is_locked == 1) {
        this.$util.Tips({
          title: "This router is locked out of service.",
        });
        return;
      }
      console.log("开始上网");
      // uni.request({
      // 	url: 'http://192.168.88.1:30098',
      // 	method: "POST",
      // 	data: uni.getStorageSync('GUID') + ' ' + '88888888',
      // 	success(res) {
      // 		console.log(res);
      // 	}
      // })
      console.log("this.getTime()===>", this.getTime());
      if (this.getTime() && this.goodsIndex == -1) {
        this.auth();
      } else {
        const unique =
          this.goodsIndex !== -1
            ? this.myGoodsList[this.goodsIndex].productValue[0].unique
            : "all";

        try {
          const res = await startMachine({
            unique,
          });
          console.log(res);
          if (res.status != 200) {
            uni.showToast({
              title: res.msg,
              icon: "none",
              duration: 2000,
            });
          }
          this.auth();
        } catch (error) {
          uni.showToast({
            title: error,
            icon: "none",
            duration: 2000,
          });
        }
      }
    },
    closePopup() {
      this.startInsert = false;

      this.coinNumber =
        parseFloat(this.coinNumber) + parseFloat(this.droppingCoinNumber);
      this.onStopCoinBgPlayer();
      setTimeout(() => {
        const message = "Endcoin";
        clearInterval(this.timer);
        // 发布消息到指定的topic
        // this.client.publish('PISO_WIFI/Pub/Play_1', message, {
        this.client.publish(
          this.coinPubTopic,
          message,
          {
            qos: 2,
          },
          (err) => {
            if (err) {
              console.error("Failed to publish message", err);
            } else {
              console.log("Message published successfully");
            }
            this.client.end(); // 断开连接
          }
        );
      }, 2000);
    },
    login() {
      let that = this;
      loginNew({
        account: that.account,
        password: 88888888,
        router_mac: that.routerMac,
        mac: that.mac,
      })
        .then(({ data }) => {
          console.log(data);
          uni.setStorageSync("GUID", data.info.account);
          that.account = data.info.account;
          that.infoMac = data.info.mac;
          that.uid = data.info.uid;
          that.package = data.package;
          that.coinNumber = data.info.integral || 0;
          console.log(that.uid);
          that.$store.commit("LOGIN", {
            token: data.token,
            time: data.expires_time - that.$Cache.time(),
          });
          this.checkRealInternetConnection();
          this.machineList();
          this.loadProducts();
          this.fetchRouter();
          this.startCountDown();
          sendMagToAllMachine();
        })
        .catch((e) => {
          this.keyLock = true;
          that.$util.Tips({
            title: e,
          });
        });
    },
    insertCoin() {
      if (this.routerDetail.is_locked == 1) {
        this.$util.Tips({
          title: "This router is locked out of service.",
        });
        return;
      }

      if (this.machines.length > 0 && !this.show) {
        const idx = (this.selectedMachineIndex = this.machines.findIndex(
          (m) => m.isAvailable == 1
        ));
        if (idx !== -1) {
          this.onMachineChange(idx, this.machines[idx]);
        }
      }

      if (this.machines.length > 1 && !this.show) {
        this.chooseMachine();
        return;
      }

      if (this.selectedMachineIndex === -1) {
        // TipUtils.showToast({
        //   title: "There are no coin acceptors available at this time.",
        // });
        // return;
        this.chooseMachine();
        return;
      }
      this.show = false;

      console.log("insertCoin===> droppingCoinNumber");
      this.droppingCoinNumber = 0;

      if (this.timer) {
        this.onStopCoinBgPlayer();
        clearInterval(this.timer);
      }
      this.countdown = 30;
      this.onPlayCoinBgPlayer();
      this.timer = setInterval(() => {
        this.countdown--;
        if (this.countdown == 0) {
          this.closePopup();
          this.countdown = 30;
        }
      }, 1000);
      this.startInsert = true;
      // this.coinNumber++
      this.connectMQTT();
    },
    generateGUID() {
      function s4() {
        return Math.floor((1 + Math.random()) * 0x1000)
          .toString(16)
          .substring(1);
      }
      return (
        s4() +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        s4() +
        s4()
      );
    },
    convertSecondsToTime(seconds) {
      const days = Math.floor(seconds / (24 * 3600));
      seconds %= 24 * 3600;
      const hours = Math.floor(seconds / 3600);
      seconds %= 3600;
      const minutes = Math.floor(seconds / 60);
      seconds %= 60;
      return `${days}d ${hours}h ${minutes}m`;
    },

    getValidityPeriod(coinNumber) {
      // 将数据按价格从高到低排序
      if (!this.myGoodsList) return;
      this.myGoodsList.sort((a, b) => b.price - a.price);
      let validity_period = 0;
      let n = coinNumber;

      // 查找第一个价格小于等于 coinNumber 的产品
      for (const product of this.myGoodsList) {
        if (n >= product.price) {
          validity_period += +product.validity_period;
          n -= +product.price;
        }
      }

      return this.convertSecondsToTime(validity_period);
    },

    connectMQTT() {
      console.log("connectMQTT===>");
      const host = "wss://mq.hirechat.net:9443/mqtt";

      const options = {
        connectTimeout: 4000,
        // clientId: 'UniAppClient_' + Math.random().toString(16).substr(2, 8),
        clientId: "GID_PISO_WIFI@@@UniAppClient_3052e0d6",
        username: "GID_PISO_WIFI@@@UniAppClient_3052e0d6",
        password: "cceGq29vKlT5I7JcZK50UhtgDfI=",
        keepAlive: 60,
        clean: true,
      };
      console.log(options);
      this.client = mqtt.connect(host, options);
      this.client.on("connect", () => {
        //console.log("Connected");
        this.isConnected = true;
        // this.client.subscribe('PISO_WIFI/Sub/Play_1', (err) => {
        console.log("connect coinSubTopic===>", this.coinSubTopic);
        this.client.subscribe(this.coinSubTopic, (err) => {
          if (!err) {
            //console.log("Subscribed to topic");
          }
        });
      });
      // 需要推送的消息内容

      const message = `Startcoin_${this.uid}_${Date.now()}_${this.coin_time}_${
        this.max_coin_num
      }_${this.beep_volume}`;
      console.log("message ====>", message);
      console.log("this.coinPubTopic ===>", this.coinPubTopic);
      // 发布消息到指定的topic
      //this.client.publish('PISO_WIFI/Pub/Play_1', message, {
      this.client.publish(
        this.coinPubTopic,
        message,
        {
          qos: 2,
        },
        (err) => {
          if (err) {
            console.error("Failed to publish message", err);
          } else {
            console.log("Message published successfully", err);
          }
          // this.client.end(); // 断开连接
        }
      );
      this.client.on("message", (topic, message) => {
        const str = message.toString();
        console.log("onMessage topic======>", topic);
        console.log("onMessage message======>", message);
        // this.topicList.push(str);
        if (str.indexOf("*") != -1) {
          this.countdown = 30;
          console.log("Received message:", topic, message.toString());
          // PISO_WIFI/Sub/Play_1 设备:1 时间:2024.06.15 15:11:24.0045  投币数量: 5

          // this.coinDevice = deviceAndSub ? deviceAndSub : null;
          // this.coinTime = time ? time: null;
          // this.topicList.push(str.split("*"));
          // this.topicList.push(str.split("*")[1]);

          this.onPlayCoinPlayer();
          this.droppingCoinNumber = Number(str.split("*")[1]) * this.price;

          // console.log("设备:", this.coinDevice);
          // console.log("时间:", this.coinTime);
          console.log("投币数量:", this.droppingCoinNumber);

          //判断上网时间
          // 示例：假设 this.coinNumber 为 1500
          const validityPeriod = this.getValidityPeriod(
            this.droppingCoinNumber
          );
          console.log(validityPeriod);
          this.coinTime = validityPeriod;
        }
      });

      this.client.on("error", (error) => {
        console.log("Connection error:", error);
        this.isConnected = false;
      });

      this.client.on("close", () => {
        //console.log("Connection closed");
        this.isConnected = false;
      });
    },
    async fetchRouter() {
      const { data } = await getRouter({
        mac: this.routerMac,
      });
      this.routerDetail = data;
    },
    formatTime(time) {
      if (!time) return 0;
      return Math.floor(time / 3600);
    },
    onSelectGoods(item, index) {
      if (item._disabled) return;
      if (this.goodsIndex === index) {
        this.goodsIndex === -1;
      } else {
        this.goodsIndex = index;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  max-width: 800rpx;
  margin: 0 auto;
  background: #ffffff;
  //   padding-top: 60rpx;
  min-height: 100vh;

  .top-balance {
    height: 260rpx;
    // width: 100%;
    font-weight: 700;
    padding: 30rpx;
    color: #fff;
    background: rgb(120, 138, 226);
    background: linear-gradient(
      45deg,
      rgba(120, 138, 226, 1) 0%,
      rgba(147, 165, 238, 1) 57%,
      rgba(182, 202, 251, 1) 100%
    );

    .balance {
      font-size: 32rpx;
      margin-bottom: 10rpx;
      position: relative;
      z-index: 999;
    }
  }
}

.package-info {
  background-color: #eee;
  padding: 20rpx;
  margin: 10rpx 40rpx;
  border-radius: 30rpx;

  .package-expiry-time {
    font-weight: 700;
    margin-top: 10rpx;
  }
}

.machine-list {
  font-size: 36rpx;
  padding: 40rpx;
  font-weight: 700;

  .card {
    background-color: #fff;
    // border-radius: 30rpx;
    margin-top: 20rpx;
    // padding: 0rpx 0 40rpx;
    position: relative;
    padding-bottom: 80rpx;
    border-radius: 30rpx;
    overflow: hidden;

    .item {
      margin-bottom: 10rpx;
      text-align: center;
      min-height: 70rpx;
      line-height: 70rpx;
      font-size: 26rpx;
    }

    .active {
      background-color: #a1b4f3;
      color: #fff;
    }

    .btn {
      // border-radius: 0 0 30rpx 30rpx;
      border-radius: 0 0 30rpx 30rpx;
      position: absolute;
      bottom: 0rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 100%;
      height: 70rpx;
      text-align: center;
      line-height: 70rpx;
      color: #fff;
      background-color: #5a6bd8;
      font-size: 34rpx;
    }
  }
}

.infoBox {
  margin-bottom: 20px;
  margin-top: 40rpx;
  .header {
    width: 80%;
    margin: 40rpx auto 30rpx;
    background-color: #d6eddb;
    // background-color: #E6E6FA;
    color: #608671;
    text-align: center;
    font-size: 26rox;
    height: 80rpx;
    line-height: 80rpx;
    font-weight: 700;
  }

  .xinhao {
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 60rpx;
      height: 60rpx;
    }

    text {
      font-size: 50rpx;
      color: #21a049;
    }
  }
}
.info {
  text-align: center;
  color: #0082ff;
  margin-top: 30rpx;
  font-weight: 26rpx;
  line-height: 50rpx;
}
.cardShow {
  z-index: 999;
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);

  .box {
    width: 80%;
    height: 700rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
    // border: 1px solid #fff;
    background-color: #fff;
    border-radius: 30rpx;
    padding: 70rpx 0;

    .title {
      // border-radius: 0 0 30rpx 30rpx;
      border-radius: 30rpx 30rpx 0 0;
      position: absolute;
      top: -4rpx;
      // left: 50%;
      // transform: translateX(-50%);
      width: 100%;
      height: 70rpx;
      text-align: center;
      line-height: 70rpx;
      color: #fff;
      background-color: #0082ff;
      font-size: 34rpx;
    }

    .item {
      // text-align: center;
      // min-height: 70rpx;
      // line-height: 70rpx;
      font-size: 26rpx;
      padding: 10rpx 30rpx;
      border-bottom: 1px solid #eee;
      position: relative;

      &:nth-last-child(1) {
        border-bottom: none;
      }
    }

    .active {
      // color: #fff;
      background-color: rgba(214, 237, 221, 0.6);
    }

    .btn {
      // border-radius: 0 0 30rpx 30rpx;
      border-radius: 0 0 30rpx 30rpx;
      position: absolute;
      bottom: -4rpx;
      // left: 50%;
      // transform: translateX(-50%);
      width: 100%;
      height: 70rpx;
      text-align: center;
      line-height: 70rpx;
      color: #fff;
      background-color: #219f4b;
      font-size: 34rpx;
    }
  }
}

.btns {
  text-align: center;
  //   padding: 40rpx;

  .btn {
    margin: 10rpx auto 30rpx;
    text-align: center;
    color: #fff;
    height: 70rpx;
    line-height: 70rpx;
  }
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 80%;
  /* height: 380rpx; */
  transform: translate(-50%, -50%);
  background-color: #fff;
  border-radius: 10px;
  z-index: 1001;
}

.popup-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-body {
  flex: 1;
  padding: 20rpx;
  /* 你的内容样式 */
}

.popup-footer {
  display: flex;
  justify-content: space-around;
  padding: 10rpx;
  border-top: 1px solid #ccc;
}

button {
  padding: 10rpx 20rpx;
  border: none;
  background-color: #007aff;
  color: #fff;
  border-radius: 5px;
}

button:hover {
  background-color: #005bb5;
}

@keyframes marquee {
  0% {
    background-position: 0 0;
  }

  100% {
    background-position: 100% 0;
  }
}

.mt {
  margin-top: 40rpx;
}

.btnDone {
  width: 400rpx;
  height: 90rpx;
  line-height: 90rpx;
  color: #fff;
  font-size: 36rpx;
  font-weight: 700;
  background-color: #780078;
  border-radius: 40rpx;
  margin: 40rpx auto 50rpx;
}

.kaleidoscope {
  width: 100%;
  height: 20px;
  background: repeating-linear-gradient(
    45deg,
    #ffd700,
    #ffd700 10%,
    #fffacd 10%,
    #fffacd 20%
  );
  background-size: 200% 100%;
  animation: marquee 2s linear infinite;
}
</style>